﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using System.IO;
using CodeCarvings.Piczard.Web;
using CodeCarvings.Piczard;
using System.Xml.Linq;
using CodeCarvings.Piczard.Filters.Watermarks;

namespace Framework.WebmasterTool
{
    public partial class SlideShow : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            siuImage.ImageRemove += new EventHandler(siuImage_ImageRemove);
            siuImage.ImageUpload += new SimpleImageUpload.ImageUploadEventHandler(siuImage_ImageUpload);
            LoadImage();
            if (!IsPostBack)
            {
                CheckPermission();
                //CleanImageUploadTemp();
                CallImageUpload();
                LoadCateBanner();
                LoadImageEdit();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.SlideShow.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        void siuImage_ImageRemove(object sender, EventArgs e)
        {
            chkWatermarkImage.Enabled = true;
        }

        void siuImage_ImageUpload(object sender, SimpleImageUpload.ImageUploadEventArgs args)
        {
            chkWatermarkImage.Enabled = false;
        }

        public void CallImageUpload()
        {
            ImageUpload(siuImage);
        }

        public void CleanImageUploadTemp()
        {
            foreach (var file in Directory.GetFiles(Server.MapPath(ConfigPaths.Path_ImageUploadTemp_Folder_MapPath)))
            {
                File.Delete(file);
            }
        }

        public void ImageUpload(SimpleImageUpload ctrImageUpload)
        {
            ctrImageUpload.ImageBackColorApplyMode = PictureTrimmerImageBackColorApplyMode.DoNotApply;
            ctrImageUpload.CropConstraint = new FreeCropConstraint();
            ctrImageUpload.PreviewFilter = new FixedResizeConstraint(200, 200, System.Drawing.Color.Black);
            ctrImageUpload.Text_BrowseButton = "Upload ảnh";
            ctrImageUpload.Text_CancelUploadButton = "Huỷ";
            ctrImageUpload.Text_EditButton = "Sửa ảnh";
            ctrImageUpload.Text_RemoveButton = "Xoá ảnh";
        }

        public void LoadCateBanner()
        {
            string levels = "|---";
            string spaces = "&nbsp;";
            List<udv_Categories> allCate = entity.udv_Categories.ToList();
            List<udv_Categories> cateBannerParent = allCate.Where(ca => ca.ParentID == 0).ToList();
            foreach (var item in cateBannerParent)
            {
                ddlCateSlide.Items.Add(new ListItem(item.Title, item.CateID.ToString()));
                LoadSubCateBanner(ref allCate, item.CateID, ref spaces, levels);
            }
        }

        public void LoadSubCateBanner(ref List<udv_Categories> allCate, int cateParentID, ref string spaces, string levels)
        {
            List<udv_Categories> subCateBanner = allCate.Where(ca => ca.ParentID == cateParentID).ToList();
            foreach (var item in subCateBanner)
            {
                ddlCateSlide.Items.Add(new ListItem(HttpUtility.HtmlDecode(spaces) + levels + item.Title, item.CateID.ToString()));
                if (entity.udv_Categories.Where(ca => ca.ParentID == item.CateID).ToList().Count > 0)
                {
                    spaces += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    LoadSubCateBanner(ref allCate, item.CateID, ref spaces, levels);
                }
            }
            if (spaces.Length > 6)
                spaces = spaces.Substring(0, spaces.Length - 36);
        }

        public void LoadImage()
        {
            List<udv_Categories> allCate = entity.udv_Categories.ToList();
            XDocument xDocImage = XDocument.Load(Server.MapPath(ConfigPaths.Path_Banner_Xml));
            var xEImage = xDocImage.Descendants("Slide").Select(sl => new { id = sl.Attribute("id").Value.Trim(), src = sl.Attribute("src").Value.Trim(), title = sl.Attribute("title").Value.Trim(), title_en = sl.Attribute("title_en").Value.Trim(), cateID = sl.Attribute("cateID").Value.Trim(), cateName = (sl.Attribute("cateID").Value == "0" ? "Trang chủ" : allCate.Where(ca => ca.CateID == int.Parse(sl.Attribute("cateID").Value)).FirstOrDefault().Title), alt = sl.Attribute("alt").Value.Trim(), link = sl.Attribute("link").Value.Trim(), index = sl.Attribute("index").Value.Trim() });
            clpImage.DataSource = xEImage.ToList();
            clpImage.BindToControl = dtlImage;
            dtlImage.DataSource = clpImage.DataSourcePaged;
        }

        protected void lkbDeleteImage_Click(object sender, EventArgs e)
        {
            int id = int.Parse((sender as LinkButton).CommandArgument);
            XDocument xDocImage = XDocument.Load(Server.MapPath(ConfigPaths.Path_Banner_Xml));
            XElement xEImage = xDocImage.Descendants("Slide").Where(sl => sl.Attribute("id").Value.Trim() == id.ToString()).FirstOrDefault();
            string srcImage = xEImage.Attribute("src").Value.Trim();
            Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageBanner_Folder_MapPath + srcImage));
            
            //create db log
            CreateDBLog(null, null, TypeAction.Delete, "Xoá slide show banner: " + xEImage.Attribute("title").Value.Trim(), "", "", "", "",
                    "", "", "", "");

            xEImage.Remove();
            xDocImage.Save(Server.MapPath(ConfigPaths.Path_Banner_Xml));
            //clear outputcache
            HttpResponse.RemoveOutputCacheItem("/Default.aspx");
            HttpResponse.RemoveOutputCacheItem("/Articles.aspx");
            HttpResponse.RemoveOutputCacheItem("/ArticleDetails.aspx");
            HttpResponse.RemoveOutputCacheItem("/Products.aspx");
            HttpResponse.RemoveOutputCacheItem("/ProductDetails.aspx");
            HttpResponse.RemoveOutputCacheItem("/Contact.aspx");
            Response.Redirect("SlideShow.aspx");
        }

        public void LoadImageEdit()
        {
            int imageID;
            if (Request.QueryString["Image"] != null)
            {
                int.TryParse(Request.QueryString["Image"].ToString(), out imageID);
                XDocument xDocImage = XDocument.Load(Server.MapPath(ConfigPaths.Path_Banner_Xml));
                XElement xEImage = xDocImage.Descendants("Slide").Where(sl => sl.Attribute("id").Value.Trim() == imageID.ToString()).FirstOrDefault();
                if (xEImage != null)
                {
                    txtImageTitle.Text = xEImage.Attribute("title").Value.Trim();
                    txtImageTitle_en.Text = xEImage.Attribute("title_en").Value.Trim();
                    txtImageAlt.Text = xEImage.Attribute("alt").Value.Trim();
                    ddlCateSlide.SelectedValue = xEImage.Attribute("cateID").Value;
                    txtImageLink.Text = xEImage.Attribute("link").Value.Trim();
                    txtDescription.Text = xEImage.Element("description").Value.Trim();
                    txtDescription_en.Text = xEImage.Element("description_en").Value.Trim();
                    txtDisplayOrder.Text = xEImage.Attribute("index").Value.Trim();
                    txtRealeaseDate.Text = xEImage.Attribute("realease_date").Value.Trim();
                    txtExpireDate.Text = xEImage.Attribute("expire_date").Value.Trim();
                    chkWatermarkImage.Enabled = false;
                    LoadImageUploadImage(xEImage);
                }
                btnImageCancel.Visible = true;
            }
        }

        public void LoadImageUploadImage(XElement xEImage)
        {
            if (xEImage.Attribute("src").Value.Trim() != "")
            {
                string sourceImageFilePath = ConfigPaths.Path_ImageBanner_Folder_MapPath + xEImage.Attribute("src").Value.Trim();
                siuImage.LoadImageFromFileSystem(Server.MapPath(sourceImageFilePath));
            }
        }

        protected void btnImageCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("SlideShow.aspx");
        }

        protected void btnImageSave_Click(object sender, EventArgs e)
        {
            XDocument xDocBanner = XDocument.Load(Server.MapPath(ConfigPaths.Path_Banner_Xml));
            if (Request.QueryString["Image"] == null)
            {
                if (siuImage.HasImage == false)
                {
                    lblMsg.Text = "Chưa upload hình ảnh slide show";
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                    return;
                }
                XElement xEBannerMaxID = xDocBanner.Descendants("Slide").OrderByDescending(sl => (int)sl.Attribute("id")).FirstOrDefault();
                int id;
                if (xEBannerMaxID == null)
                {
                    id = 0;
                }
                else
                {
                    id = int.Parse(xEBannerMaxID.Attribute("id").Value) + 1;
                }
                string fileNameImage = Globals.GetFileName(siuImage.SourceImageClientFileName);
                siuImage.SaveProcessedImageToFileSystem(ConfigPaths.Path_ImageBanner_Folder + fileNameImage);
                xDocBanner.Root.Add(new XElement("Slide",
                    new XAttribute("id", id),
                    new XAttribute("src", fileNameImage),
                    new XAttribute("title", txtImageTitle.Text.Trim()),
                    new XAttribute("title_en", txtImageTitle_en.Text.Trim()),
                    new XAttribute("cateID", ddlCateSlide.SelectedValue),
                    new XAttribute("alt", txtImageAlt.Text.Trim()),
                    new XAttribute("link", txtImageLink.Text.Trim()),
                    new XAttribute("index", txtDisplayOrder.Text.Trim()),
                    new XAttribute("realease_date", txtRealeaseDate.Text.Trim()),
                    new XAttribute("expire_date", txtExpireDate.Text.Trim()),
                    new XElement("description", new XCData(txtDescription.Text)),
                    new XElement("description_en", new XCData(txtDescription_en.Text))));
                xDocBanner.Save(Server.MapPath(ConfigPaths.Path_Banner_Xml));

                //create db log
                CreateDBLog(null, null, TypeAction.Insert, "Thêm slide show banner: " + txtImageTitle.Text.Trim(), "", "", "", "",
                        "", "", "", "");

                //clear outputcache
                HttpResponse.RemoveOutputCacheItem("/Default.aspx");
                HttpResponse.RemoveOutputCacheItem("/Articles.aspx");
                HttpResponse.RemoveOutputCacheItem("/ArticleDetails.aspx");
                HttpResponse.RemoveOutputCacheItem("/Products.aspx");
                HttpResponse.RemoveOutputCacheItem("/ProductDetails.aspx");
                HttpResponse.RemoveOutputCacheItem("/Contact.aspx");
                Response.Redirect("SlideShow.aspx");
            }
            else
            {
                if (siuImage.HasImage == false)
                {
                    lblMsg.Text = "Chưa upload hình ảnh slide show";
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                    return;
                }
                int imageID;
                int.TryParse(Request.QueryString["Image"].ToString(), out imageID);
                XElement xEImage = xDocBanner.Descendants("Slide").Where(sl => sl.Attribute("id").Value.Trim() == imageID.ToString()).FirstOrDefault();
                if (siuImage.HasNewImage == true)
                {
                    Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageBanner_Folder_MapPath + xEImage.Attribute("src").Value.Trim()));
                    string fileNameImage = Globals.GetFileName(siuImage.SourceImageClientFileName);
                    siuImage.SaveProcessedImageToFileSystem(ConfigPaths.Path_ImageBanner_Folder + fileNameImage);
                    xEImage.Attribute("src").Value = fileNameImage;
                }
                string oldTitle = xEImage.Attribute("title").Value;
                xEImage.Attribute("title").Value = txtImageTitle.Text.Trim();
                xEImage.Attribute("title_en").Value = txtImageTitle_en.Text.Trim();
                xEImage.Attribute("cateID").Value = ddlCateSlide.SelectedValue;
                xEImage.Attribute("alt").Value = txtImageAlt.Text.Trim();
                xEImage.Attribute("link").Value = txtImageLink.Text.Trim();
                xEImage.Attribute("index").Value = txtDisplayOrder.Text.Trim();
                xEImage.Attribute("realease_date").Value = txtRealeaseDate.Text.Trim();
                xEImage.Attribute("expire_date").Value = txtExpireDate.Text.Trim();
                xEImage.Element("description").ReplaceNodes(new XCData(txtDescription.Text));
                xEImage.Element("description_en").ReplaceNodes(new XCData(txtDescription_en.Text));
                xDocBanner.Save(Server.MapPath(ConfigPaths.Path_Banner_Xml));

                //create db log
                CreateDBLog(null, null, TypeAction.Update, "Cập nhật slide show banner: " + oldTitle + " - " + txtImageTitle.Text.Trim(), "", "", "", "",
                        "", "", "", "");

                //clear outputcache
                HttpResponse.RemoveOutputCacheItem("/Default.aspx");
                HttpResponse.RemoveOutputCacheItem("/Articles.aspx");
                HttpResponse.RemoveOutputCacheItem("/ArticleDetails.aspx");
                HttpResponse.RemoveOutputCacheItem("/Products.aspx");
                HttpResponse.RemoveOutputCacheItem("/ProductDetails.aspx");
                HttpResponse.RemoveOutputCacheItem("/Contact.aspx");
                Response.Redirect("SlideShow.aspx");
            }
        }

        protected void chkWatermarkImage_CheckedChanged(object sender, EventArgs e)
        {
            if (chkWatermarkImage.Checked == true && siuImage.HasImage == false)
            {
                XDocument xDocWatermark = XDocument.Load(Server.MapPath(ConfigPaths.Path_Watermark_Xml));
                XElement xEImage = xDocWatermark.Descendants("img").FirstOrDefault();
                siuImage.PostProcessingFilter = new ImageWatermark(Server.MapPath(ConfigPaths.Path_ImageUpload_Folder_MapPath + xEImage.Value), System.Drawing.ContentAlignment.BottomRight);
            }
            else if (chkWatermarkImage.Checked == false && siuImage.HasImage == false)
            {
                siuImage.PostProcessingFilter = null;
            }
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}